﻿using System.IO;
using System.Web;
using IterationLife.Extensions.Qiniu;
using IterationLife.System.Models;
using IterationLife.System.Repositories;
using Util.Exceptions;

namespace IterationLife.System.Services
{
    /// <summary>
    /// 附件管理
    /// </summary>
    public class AttachmentManager : IAttachmentManager
    {
        /// <summary>
        /// 附件仓储
        /// </summary>
        protected IAttachmentRepository AttachmentRepository { get; set; }

        /// <summary>
        /// 初始化附件管理
        /// </summary>
        /// <param name="attachmentRepository">附件仓储</param>
        public AttachmentManager(IAttachmentRepository attachmentRepository)
        {
            AttachmentRepository = attachmentRepository;
        }

        /// <summary>
        /// 上传
        /// </summary>
        public Attachment Upload(string id)
        {
            var fromFile = GetUploadFile(id);
            var entity = CreateEntity(fromFile.FileName, fromFile.ContentLength);
            QiNiu.Upload(fromFile.InputStream, entity.Address);
            AttachmentRepository.Add(entity);
            return entity;
        }

        /// <summary>
        /// 上传
        /// </summary>
        public Attachment Upload(byte[] fileBytes, int size, string fileName)
        {
            var entity = CreateEntity(fileName, size);
            QiNiu.Upload(fileBytes, entity.Address);
            AttachmentRepository.Add(entity);
            return entity;
        }

        /// <summary>
        /// 上传
        /// </summary>
        public Attachment Upload(Stream inputStream, int size, string fileName)
        {
            var entity = CreateEntity(fileName, size);
            QiNiu.Upload(inputStream, entity.Address);
            AttachmentRepository.Add(entity);
            return entity;
        }

        private Attachment CreateEntity(string fileName, int size)
        {
            var entity = new Attachment
            {
                Name = fileName,
                Size = size,
                Extensions = Path.GetExtension(fileName).Replace(".", "").ToLower(),
            };
            entity.Init();
            entity.Address = $"{entity.Id}.{entity.Extensions}";
            return entity;
        }

        private HttpPostedFile GetUploadFile(string id)
        {
            var formFile = HttpContext.Current.Request.Files[id];
            if (formFile == null)
                throw new Warning("未查询到上传文件");
            return formFile;
        }


    }
}
